<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col>
        <el-button type="primary" plain @click="save">保存</el-button>
        <el-button type="warning" plain @click="selectSites">多场地使用此模板</el-button>
      </el-col>
    </el-row>

    <FullCalendar ref="fullCalendar" :options="calendarOptions" class="mbFullC">
      <template #eventContent="arg">
        <div class="text-center" style="line-height: 50px;">
          <b>{{ arg.event.title }}</b>
        </div>
        <!--<b>{{ arg.timeText }}</b>-->
      </template>
    </FullCalendar>

    <el-dialog v-model="open" title="关联定价模板" @close="dialogClose">
      <el-table :data="tableData">
        <el-table-column type="index" />
        <el-table-column label="模板名称" prop="templateName" min-width="150" />
        <el-table-column label="模板类型" prop="templateTypeStr" min-width="120" />
        <el-table-column label="操作" align="center" fixed="right" width="100">
          <template #default="scope">
            <el-button type="text" @click="chooseTemplate(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <dialogSiteList ref="dialogSite" @submitForm="multiEdit" />
  </div>
</template>
<script setup>
import '@fullcalendar/core/vdom'
import FullCalendar from '@fullcalendar/vue3'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import { onMounted, reactive, ref } from '@vue/runtime-core'
import { toRefs } from '@vueuse/shared'
import useVenStore from '../../../../../store/modules/ven'
import { getSitePrice, priceTemplateList, saveSitePrice, sitePriceMultiEdit } from '../../../../../api/ven'
import { dayjs } from 'element-plus'
import { getCurrentInstance } from 'vue'
import { getDayStr, getHourStr, getTimeUsed } from '../../../../../utils/ruoyi'
import { useRoute } from 'vue-router'
import dialogSiteList from '../components/dialog/siteList'


const venStore = useVenStore()
const { proxy } = getCurrentInstance()
const route = useRoute()

const data = reactive({
  calendarOptions: {
    plugins: [
      dayGridPlugin,
      timeGridPlugin,
      interactionPlugin // needed for dateClick
    ],
    initialView: 'timeGridWeek',
    firstDay: 1,
    locale: 'zh-cn',
    aspectRatio: 3,
    headerToolbar: {
      left: '',
      center: '',
      right: ''
    },
    dayHeaderFormat: {
      weekday: 'short' //  'ddd M/d'
    },
    slotLabelFormat: {
      hour: '2-digit',
      minute: '2-digit',
      meridiem: false,
      hour12: false // 设置时间为24小时
    },
    allDaySlot: false,
    slotMinTime: `${venStore.businessPeriod[0].split(':')[0]}:00`, // 设置显示的时间从几点开始
    slotMaxTime: `${parseInt(venStore.businessPeriod[1].split(':')[0]) + (parseInt(venStore.businessPeriod[1].split(':')[1]) === 0 ? 0 : 1)}:00`, // 设置显示的时间从几点结束
    slotDuration: '01:00:00',
    // events: [],
    editable: false, // 是否可以进行（拖动、缩放）修改
    selectable: true,
    selectMirror: true,
    dayMaxEvents: true,
    eventMinHeight: 50,
    height: '65vh',
    weekends: true,
    select: handleDateSelect,
    eventClick: handleEventClick
  },
  open: false,
  tableData: []
})
const { calendarOptions, open, tableData } = toRefs(data)
// const dialogSite = ref(null)

const timeUsed = getTimeUsed(venStore.businessPeriod[0], venStore.businessPeriod[1])
let currentSitePrice = null
let selectedCalendar = null
let calendarApi = null

const getCalendarApi = () => {
  if (!calendarApi) {
    calendarApi = proxy.$refs.fullCalendar.getApi()
  }
  return calendarApi
}

onMounted(() => {
  getSitePrice(route.params.siteId)
    .then((res) => {
      if (res.data) {
        currentSitePrice = res.data
        const priceInfo = JSON.parse(currentSitePrice.priceInfo)
        const now = dayjs().minute(0).second(0).millisecond(0)

        _.chain().range(7).each((day) => {
          let startTime = now.day(day + 1)
          _.each(timeUsed, (t, hour) => {
            if (t.used) {
              const commonPrice = priceInfo[0][day][hour]
              const memberPrice = priceInfo[1][day][hour]
              if ((memberPrice !== '-1' && commonPrice !== '-1') && (memberPrice !== '0' || commonPrice !== '0')) {
                startTime = startTime.hour(hour)
                const endTime = startTime.add(1, 'hour')
                const title = `普通价 ¥${commonPrice} / 会员价 ￥${memberPrice}`

                getCalendarApi().addEvent({
                  day,
                  hour,
                  memberPrice,
                  commonPrice,
                  title,
                  start: startTime.toDate(),
                  end: endTime.toDate()
                })
              }
            }
          })
        }).value()
      }
    })

  priceTemplateList({
    status: 1
  }).then(res => {
    tableData.value = res.rows
  })
})

const getPriceInfo = () => {
  const memberPrice = []; const commonPrice = []
  _.chain().range(7).each((day) => {
    const memberPriceDay = []; const commonPriceDay = []
    _.each(timeUsed, (t, hour) => {
      if (t.used) {
        const event = _.find(getCalendarApi().getEvents(), (e) => {
          return e.extendedProps.day == day && e.extendedProps.hour == hour
        })
        if (event) {
          memberPriceDay.push(event.extendedProps.memberPrice)
          commonPriceDay.push(event.extendedProps.commonPrice)
        } else {
          memberPriceDay.push('0')
          commonPriceDay.push('0')
        }
      } else {
        memberPriceDay.push('-1')
        commonPriceDay.push('-1')
      }
    })
    memberPrice.push(memberPriceDay)
    commonPrice.push(commonPriceDay)
  }).value()

  return JSON.stringify([commonPrice, memberPrice])
}

function save() {
  saveSitePrice({
    id: currentSitePrice?.id,
    siteId: route.params.siteId,
    priceInfo: getPriceInfo()
  }).then(() => {
    proxy.$modal.msgSuccess('保存成功', () => {
      proxy.$tab.closeOpenPage({ name: 'Pricing' })
    })
  })
}

function chooseTemplate(template) {
  const priceArray = JSON.parse(template.priceArray)
  let startTime = dayjs(selectedCalendar.start)
  const endTime = dayjs(selectedCalendar.end)

  while (startTime < endTime) {
    let day = startTime.day() - 1
    if (day < 0) {
      day = 6
    }
    const hour = startTime.hour()
    const tempEnd = startTime.add(1, 'hour')
    const commonPrice = priceArray[0][hour]
    const memberPrice = priceArray[1][hour]
    const title = `普通价 ¥${commonPrice} / 会员价 ￥${memberPrice}`

    const event = _.find(getCalendarApi().getEvents(), (e) => {
      return e.extendedProps.day == day && e.extendedProps.hour == hour
    })
    if (event) {
      event.setProp('title', title)
      event.setExtendedProp('commonPrice', commonPrice)
      event.setExtendedProp('memberPrice', memberPrice)
    } else {
      getCalendarApi().addEvent({
        day,
        hour,
        memberPrice,
        commonPrice,
        title,
        start: startTime.toDate(),
        end: tempEnd.toDate()
      })
    }

    startTime = tempEnd
  }

  open.value = false
}

function dialogClose() {
  selectedCalendar = null
}

function handleDateSelect(selectInfo) {
  const calendarApi = selectInfo.view.calendar
  calendarApi.unselect() // clear date selection

  selectedCalendar = selectInfo
  open.value = true
}

function handleEventClick(clickInfo) {
  const dayStr = getDayStr(clickInfo.event.extendedProps.day)
  const hourStr = getHourStr(clickInfo.event.extendedProps.hour)

  proxy.$modal.confirm(`确定删除 ${dayStr} 时间段 ${hourStr} 的价格 ${clickInfo.event.title} ？`)
    .then(function() {
      clickInfo.event.remove()
    })
}

function selectSites() {
  proxy.$refs.dialogSite.open()
}

function multiEdit(siteIds) {
  sitePriceMultiEdit({
    ids: siteIds,
    priceInfo: getPriceInfo()
  }).then(() => {
    proxy.$modal.msgSuccess('保存成功', () => {
      proxy.$refs.dialogSite.close()
    })
  })
}

</script>

<style scoped>
</style>
